package com.factory;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Properties;

public class BeanFactory {

  private static Properties env = null;

  static {

    env = new Properties();

    InputStream resourceAsStream = BeanFactory.class.getResourceAsStream("/beans.properties");

    try {
        env.load(resourceAsStream);
    }catch (Exception e){

      e.printStackTrace();
    }

  }

  public static <T> T getBean(Class<T> clazz){

    String[] splitNames = clazz.getName().split("\\.");

    if (splitNames.length == 0){
      return null;
    }

    String key = splitNames[splitNames.length - 1 ].toLowerCase();
    String classReference = env.getProperty(key);
    if (classReference.isEmpty()){
      return null;
    }

    try {

      Class cla = Class.forName(classReference);

      T t =(T)cla.newInstance();
      return  t;
    }catch (Exception e){
      return  null;
    }

  }

}
